<script setup>
import Message from 'vue-m-message'
import businessService from '@/api/business/index.js'
import businessTemplateService from '@/api/businessTemplate/index.js'
import contractService from '@/api/contract/index.js'
import customerInformationService from '@/api/customerInformation/index.js'
import userServices from '@/api/user/user.js'
import FileUpload from '@/components/FileUpload/index.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useDict } from '@/utils/dict.js'
import { tableCheckChane, uniqueBy } from '@/utils/index.js'
import { isValidMobile } from '@/utils/validate.js'

const emit = defineEmits(['update:visible'])
const dialogVisible = defineModel('visible', {
  type: Boolean,
})
const contractId = defineModel('contractId', {
  type: String,
})
const formDisabled = defineModel('formDisabled', {
  type: Boolean,
  default: false,
})
const contractAmountData = ref([])
const contractAmountColumns = ref([
  {
    title: '业务名称',
    field: 'businessName',
    align: 'center',
  },
  {
    title: '业务类别',
    field: 'businessType',
    align: 'center',
    slots: { default: 'businessType' },
  },
  {
    title: '代理费',
    field: 'agencyFee',
    align: 'center',
    slots: { default: 'agencyFee' },
  },
  {
    title: '官费',
    align: 'center',
    children: [
      {
        title: '申请费',
        field: 'filingFee',
        align: 'center',
        slots: { default: 'filingFee' },
      },
      {
        title: '实审费',
        field: 'auditFee',
        align: 'center',
        slots: { default: 'auditFee' },
      },
      // {
      //   title: '登记费',
      //   label: 'registerFee',
      //   align: 'center',
      //   slots: { default: 'registerFee' },
      // },
    ],
  },
  {
    title: '其他费用',
    field: 'otherFee',
    align: 'center',
    slots: { default: 'otherFee' },
  },
  {
    title: '应收费用',
    field: 'receivableFee',
    align: 'center',
  },
  {
    title: '数量',
    field: 'amount',
    align: 'center',
    slots: { default: 'amount' },
  },
  {
    title: '合计',
    field: 'total',
    align: 'center',
  },
  {
    title: '操作',
    field: 'action',
    align: 'center',
    slots: { default: 'action' },
  },
])
const businessTemplateList = ref([])
const {
  sys_contract_type,
  sys_contractaame,
  sys_contract_status,
  sys_case_type,
  sys_product_name,
  sys_proceeds_time,
} = useDict('sys_contract_type', 'sys_contractaame', 'sys_contract_status', 'sys_case_type', 'sys_product_name', 'sys_proceeds_time')
const contractFormRef = ref(null)
const contractForm = ref({
  isBigContract: 1,
  isDiscounts: 1,
  isMultiPerson: 1,
  isHand: 0,
  isMoney: 0,
})
const contractFormRules = ref({
  customerId: [
    {
      required: true,
      message: '请选择客户',
      trigger: 'change',
    },
  ],
  contractName: [
    {
      required: true,
      message: '请输入合同名称',
      trigger: 'blur',
    },
  ],
  subjectId: [
    {
      required: true,
      message: '请选择签约主体',
      trigger: 'change',
    },
  ],
  otherFee: [
    {
      required: true,
      message: '请输入第三方费用',
      trigger: 'blur',
    },
  ],
  contractStartTime: [
    {
      required: true,
      message: '请选择合同开始时间',
      trigger: 'change',
    },
  ],
  contractEndTime: [
    {
      required: true,
      message: '请选择合同结束时间',
      trigger: 'change',
    },
  ],
  submitcompanyId: [
    {
      required: true,
      message: '请选择递交端口',
      trigger: 'change',
    },
  ],
  patentpersonId: [
    {
      required: true,
      message: '请选择专利权人',
      trigger: 'blur',
    },
  ],
  caseType: [
    {
      required: true,
      message: '请选择案件方式',
      trigger: 'change',
    },
  ],
  linkmanMail: [
    {
      required: true,
      message: '请输入联系人邮箱',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  linkmanPhone: [
    {
      required: true,
      message: '请输入联系人电话',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (!isValidMobile(value)) {
          callback(new Error('请输入正确的手机号码'))
        }
        callback()
      },
    },
  ],
  patentLinkman: [
    {
      required: true,
      message: '请输入专利权人联系人',
      trigger: 'blur',
    },
  ],
})

const customerList = ref([])
const distributorList = ref([])
const contractQueryList = ref([])
const companyQueryList = ref([])
const customerQueryList = ref([])

const contractAmountVisible = ref(false)
const contractAmountSearConfig = ref([
  {
    label: '业务类别',
    type: 'select',
    field: 'businessType',
    options: {
      data: sys_product_name,
    },
  },
  {
    label: '业务名称',
    field: 'businessName',
    type: 'input',
  },
])
const contractAmountQueryParam = ref({})
const contractAmountTableData = ref([])
const contractAmountTableColumns = ref([
  {
    type: 'checkbox',
    width: 50,
    align: 'center',
  },
  {
    type: 'seq',
    width: 60,
    align: 'center',
  },
  {
    title: '业务类别',
    field: 'businessType',
    align: 'center',
    slots: { default: 'businessType' },
  },
  { title: '业务名称', field: 'businessName', align: 'center' },
  { title: '代理费用', field: 'agencyFee', align: 'center' },
  { title: '其他费用', field: 'otherFee', align: 'center' },
  { title: '关联流程', field: 'flowName', align: 'center' },
  { title: '备注', field: 'remark', align: 'center' },
])
const contractAmountPageConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

const isReduce = ref(1)
const addBusinessIds = ref([])
const activeName = ref(['1', '2', '3', '4', '5'])
const paymentNodeData = ref([])
const paymentNodeColumns = ref([
  {
    title: '业务名称',
    field: 'businessName',
    align: 'center',
  },
  {
    title: '收款时间节点',
    field: 'receiptNode',
    align: 'center',
    slots: { default: 'receiptNode' },
  },
  {
    title: '代理费',
    field: 'agencyFee',
    align: 'center',
    slots: { default: 'agencyFee' },
  },
  // {
  //   title: '官费',
  //   field: 'officerFee',
  //   align: 'center',
  //   slots: { default: 'officerFee' },
  // },
  {
    title: '其他费用',
    field: 'otherFee',
    align: 'center',
    slots: {
      default: 'otherFee',
    },
  },
  {
    title: '操作',
    field: 'action',
    align: 'center',
    slots: { default: 'action' },
    width: 180,
  },
])
const paymentNodeContentData = ref([])
const partMoneyList = ref([])
const businessRateColumns = ref([
  {
    title: '角色',
    field: 'roleName',
    align: 'center',
    slots: { default: 'roleName' },
  },
  {
    title: '人员',
    field: 'userName',
    align: 'center',
    slots: { default: 'userName' },
  },
  {
    title: '比例(%)',
    field: 'proportion',
    align: 'center',
    slots: { default: 'proportion' },
  },
  {
    title: '备注',
    field: 'remark',
    align: 'center',
    slots: { default: 'remark' },
  },
  {
    title: '操作',
    field: 'action',
    align: 'center',
    slots: { default: 'action' },
  },
])

const salesmanOptions = ref()
const roleOptions = reactive([
  {
    value: '1',
    label: '业务经理',
  },
  {
    value: '2',
    label: '第二协助人',
  },
  {
    value: '3',
    label: '第三协助人',
  },
])

const totalAmount = ref(0)
const formLoading = ref(false)
const mergeFooterItems = ref()

watch(() => dialogVisible.value, (newVal, oldVal) => {
  if (newVal) {
    handleGetContractData()
    handleGetSalesmanOptions()
  }
})

function handleGetContractDataDetail() {
  contractAmountData.value = []
  contractService.getDetail(contractId.value).then((res) => {
    const { sysContractAmountVos, sysContractReceiptNodeVos } = res.data
    contractForm.value = res.data
    formLoading.value = false
    contractAmountData.value = sysContractAmountVos.map(item => ({
      ...item,
      businessId: item.patentType,
    }))
    partMoneyList.value = res.data.partMoneyList
    paymentNodeData.value = uniqueBy(sysContractAmountVos, 'businessName').map((item, index) => {
      return {
        businessName: item.businessName,
        type: index + 1,
      }
    })
    if (sysContractReceiptNodeVos?.length > 0) {
      paymentNodeContentData.value = sysContractReceiptNodeVos.reduce((accumulator, current) => {
        const existingGroup = accumulator.find(group => group[0].patentType === current.patentType)
        if (existingGroup) {
          // 如果已经存在这个分组，则添加到分组中
          existingGroup.push(current)
        }
        else {
          // 否则创建新的分组
          accumulator.push([current])
        }
        return accumulator
      }, [])
    }
    contractForm.value.isBigContract = Number(contractForm.value.isBigContract)
    contractForm.value.patentpersonId = contractForm.value.patentpersonId.split(',')
    contractForm.value.templateName = res.data.businessTemplate?.templateId
    contractForm.value.isDiscounts = Number(res.data.isDiscounts)
    contractForm.value.isMultiPerson = Number(res.data.isMultiPerson)
    contractForm.value.isHand = Number(res.data.isHand)
    contractForm.value.isMoney = Number(res.data.isMoney)
    delete contractForm.value.sysContractAmountVos
    delete contractForm.value.sysContractReceiptNodeVos
    mergeFooterItems.value = [
      { row: 0, col: 0, rowspan: 9, colspan: 13 },
    ]
  })
}

async function handleGetContractData() {
  getBusinessTemplateList()
  handleGetCustomerInformationList()
  handleGetSalesmanOptions()
  const queryRes = await customerInformationService.getQueryList()
  const distributorRes = await contractService.getDistributorList()
  const subjectRes = await contractService.getSubjectContractList()
  const submitCompanyRes = await contractService.getSubmitCompanyList()
  customerList.value = queryRes.data
  distributorList.value = distributorRes.data
  contractQueryList.value = subjectRes.data
  companyQueryList.value = submitCompanyRes.data
  contractForm.value.contractType = sys_contract_type.value[0].value
}

function handleGetCustomerInformationList() {
  contractService.getCustomerInformationList().then((res) => {
    customerQueryList.value = res.data
  })
}

function handleGetSalesmanOptions() {
  userServices.getSalesmanList().then((res) => {
    salesmanOptions.value = res.data
  })
}

function getBusinessTemplateList() {
  businessTemplateService.list().then((res) => {
    businessTemplateList.value = res.rows
    contractForm.value.templateName = '1798641089136635905'
    getBusinessList()
  })
}

function getBusinessList() {
  const templateId = contractForm.value.templateName
  const businessIds = contractAmountData.value.filter(item => item.businessId).map(item => item.businessId)
  businessTemplateService.businessList(templateId, businessIds.join(',')).then((res) => {
    // 更新合同金额数据
    const updatedContractAmountData = res.data.map((item, index) => {
      // 更新每个合同项的字段
      item.auditFee = 0
      item.registerFee = 0
      item.amount = item.amount || 0
      item.total = 0
      handleCalculateReceivableFee(item)
      return {
        ...item,
        paymentNode: {
          businessName: item.businessName,
          type: index + 1,
        },
        paymentNodeContent: [
          {
            patentType: item.businessId,
            businessName: item.businessName,
            receiptNode: '',
            agencyFee: 0,
            officerFee: 0,
            otherFee: 0,
          },
          {
            patentType: item.businessId,
            businessName: item.businessName,
            receiptNode: '',
            agencyFee: 0,
            officerFee: 0,
            otherFee: 0,
          },
        ],
      }
    })
    // 提取付款节点数据和付款节点内容数据
    paymentNodeData.value = updatedContractAmountData.map(item => item.paymentNode)
    paymentNodeContentData.value = updatedContractAmountData.map(item => item.paymentNodeContent)
    // 更新合同金额数据
    contractAmountData.value = updatedContractAmountData
    mergeFooterItems.value = [
      { row: 0, col: 0, rowspan: 9, colspan: 13 },
    ]
    partMoneyList.value = [
      {
        roleName: '',
        userName: '',
        proportion: 0,
        remark: '',
      },
    ]
    if (contractId.value) {
      formLoading.value = true
      handleGetContractDataDetail()
    }
  })
}

function handleChangeReduce() {
  contractAmountData.value.forEach((item) => {
    handleCalculateReceivableFee(item)
  })
}

function handleAmountChange(row) {
  // const totalFees = Number(row.agencyFee) + Number(row.filingFee) + Number(row.auditFee) + Number(row.registerFee) + Number(row.otherFee)
  const totalFees = Number(row.agencyFee) + Number(row.otherFee)
  row.receivableFee = Math.floor(totalFees)
  if (row.amount >= 1) {
    row.total = Math.floor(totalFees * row.amount)
  }
}

const footerData = computed(() => {
  const data = contractAmountData.value
  const totalSum = data.reduce((accumulator, current) => {
    return Math.floor(accumulator + Number(current.total))
  }, 0)
  totalAmount.value = data.length > 0 ? totalSum : 0
  return data.length > 0
    ? [
        { businessName: `总合计： ${totalSum}` },
      ]
    : []
})

function handleAddAmount() {
  const excludedIds = contractAmountData.value.map(item => item.businessId)
  const params = {
    ...contractAmountQueryParam.value,
    excludedIds: excludedIds.join(','),
    pageNum: contractAmountPageConfig.value.currentPage,
    pageSize: contractAmountPageConfig.value.pageSize,
  }
  businessService.list(params).then((res) => {
    contractAmountTableData.value = res.rows
    contractAmountPageConfig.value.total = res.total
    contractAmountVisible.value = true
  })
}

function handleContractAmountSearch(e) {
  contractAmountQueryParam.value = e
  handleAddAmount()
}

function handleContractAmountCheckChange(data) {
  addBusinessIds.value = tableCheckChane(data, 'businessId', addBusinessIds.value)
}

function handleAddContractAmount() {
  const data = contractAmountTableData.value
  const ids = addBusinessIds.value
  const newData = data.filter(item => ids.includes(item.businessId))
  newData.forEach((item) => {
    item.auditFee = 0
    item.registerFee = 0
    item.amount = item.amount || 0
    item.total = 0
    handleCalculateReceivableFee(item)
  })
  contractAmountData.value = [...contractAmountData.value, ...newData]
  paymentNodeData.value = [...paymentNodeData.value, ...newData.map((item, index) => {
    return {
      businessName: item.businessName,
      type: index + paymentNodeData.value.length + 1,
    }
  })]
  paymentNodeContentData.value = [...paymentNodeContentData.value, ...newData.map((item) => {
    return [
      {
        patentType: item.businessId,
        businessName: item.businessName,
        receiptNode: '',
        agencyFee: 0,
        officerFee: 0,
        otherFee: 0,
      },
      {
        patentType: item.businessId,
        businessName: item.businessName,
        receiptNode: '',
        agencyFee: 0,
        officerFee: 0,
        otherFee: 0,
      },
    ]
  })]
  contractAmountVisible.value = false
  addBusinessIds.value = []
  mergeFooterItems.value = [
    { row: 0, col: 0, rowspan: 9, colspan: 13 },
  ]
}

/**
 * @description: 计算合同金额
 * @param {object} item - 数据信息
 */
function handleCalculateReceivableFee(item) {
  const isDiscount = contractForm.value.isDiscounts
  const isMultiPerson = contractForm.value.isMultiPerson
  const isMoney = contractForm.value.isMoney
  console.log(isMoney)
  const feeConfig = {
    '1796024658129670146': { filingFee: isDiscount === 0 ? isMultiPerson === 0 ? 150 : 75 : 500 },
    '1798631228967981058': { filingFee: isDiscount === 0 ? isMultiPerson === 0 ? 370 : 185 : 950, auditFee: isDiscount === 0 ? isMultiPerson === 0 ? 750 : 375 : 2500 },
    '1798631332965748738': { filingFee: isDiscount === 0 ? isMultiPerson === 0 ? 150 : 75 : 500 },
  }
  if (isMoney === 1) {
    item.agencyFee = 0
    item.otherFee = 0
    item.receivableFee = 0
    paymentNodeContentData.value = paymentNodeContentData.value.map(innerArray =>
      innerArray.map(patent =>
        ({ ...patent, agencyFee: 0, officerFee: 0, otherFee: 0, receiptNode: '' }),
      ),
    )
  }
  const config = feeConfig[item.businessId] || {}
  item.filingFee = config.filingFee || 0
  item.auditFee = config.auditFee || 0
  item.agencyFee = Math.floor(item.agencyFee)
  item.otherFee = Math.floor(item.otherFee)
  // item.receivableFee = Math.floor(item.agencyFee + item.filingFee + item.auditFee + item.registerFee + item.otherFee)
  item.receivableFee = Math.floor(item.agencyFee + item.otherFee)
  if (item.amount >= 1) {
    item.total = Math.floor(item.receivableFee * item.amount)
  }
}

function getContentSelectData(row, list) {
  return list.filter((item) => {
    return !((row.businessName === '外观设计专利' || row.businessName === '实用新型专利') && item.label === '实审')
  })
}

function handlePaymentNodeChange(index) {
  const values = paymentNodeContentData.value[index].map((item) => {
    return item.receiptNode
  })
  values.forEach((item, i) => {
    if (item !== '') {
      if (values.indexOf(item) !== i) {
        Message.warning('收款时间节点不能重复', {
          zIndex: 9999,
        })
        paymentNodeContentData.value[index][i].receiptNode = ''
      }
    }
  })
}

/**
 * 处理付款节点的添加或删除操作。
 *
 * @param {number} index - 付款节点数据的索引
 * @param {string} type - 操作类型，'add' 或 'remove'
 * @param {object} data - 当前操作涉及的数据对象
 */
function handleActionPaymentNode(index, type, data) {
  // 获取当前索引对应的付款节点内容数据
  const currentData = paymentNodeContentData.value[index]
  // 获取当前操作涉及的业务名称
  const currentBusinessName = data.businessName
  // 如果操作类型为 'add'
  if (type === 'add') {
    // 在合同金额数据中找到匹配的业务项并添加新的付款节点
    const newNodes = uniqueBy(contractAmountData.value, 'businessName')
      .filter(item => item.businessName === currentBusinessName)
      .map(item => ({
        patentType: item.businessId,
        businessName: item.businessName,
        receiptNode: '',
        agencyFee: 0,
        officerFee: 0,
        otherFee: 0,
      }))
    currentData.push(...newNodes)
  }
  // 如果操作类型为 'remove'
  else if (type === 'delete') {
    // 从当前付款节点内容数据中移除最后一个节点
    if (currentData.length > 0) {
      currentData.pop()
    }
    else {
      Message.warning('没有可移除的付款节点', {
        zIndex: 9999,
      })
    }
  }
}
/**
 * 处理删除合同金额和付款节点数据。
 * @param {object} row - 要删除的行数据
 */
function handleDelAmount(row) {
  // 找到要删除的合同金额数据的索引
  const contractIndex = contractAmountData.value.findIndex(item => item === row)
  // 如果找到了要删除的合同金额数据
  if (contractIndex !== -1) {
    // 删除合同金额数据
    contractAmountData.value.splice(contractIndex, 1)
  }
  // 找到要删除的付款节点数据的索引
  const paymentIndex = paymentNodeData.value.findIndex(item => item.businessName === row.businessName)
  // 如果找到了要删除的付款节点数据
  if (paymentIndex !== -1) {
    // 删除付款节点数据
    paymentNodeData.value.splice(paymentIndex, 1)
  }
  mergeFooterItems.value = [
    { row: 0, col: 0, rowspan: 9, colspan: 13 },
  ]
}

function handleClearAmount() {
  contractAmountData.value = []
  paymentNodeData.value = []
  paymentNodeContentData.value = []
  mergeFooterItems.value = [
    { row: 0, col: 0, rowspan: 9, colspan: 13 },
  ]
}

function handleAddBusinessRate() {
  partMoneyList.value.push({
    roleName: '',
    userName: '',
    proportion: 0,
    remark: '',
  })
}

function handleDelBusinessRate(row) {
  partMoneyList.value.splice(partMoneyList.value.indexOf(row), 1)
}

function handleSubmit() {
  contractFormRef.value.validate((valid) => {
    if (valid) {
      const sysContractReceiptNodeBos = paymentNodeContentData.value.flat()
      const hasZeroAmount = contractAmountData.value.some(item => item.amount === 0)
      if (contractForm.value.isBigContract === 1 && contractForm.value.isMoney === 0) {
        if (hasZeroAmount) {
          return Message.error('合同金额数量不能为0！', {
            zIndex: 9999,
          })
        }
      }
      contractAmountData.value.forEach((item) => {
        item.officerFee = Number(item.filingFee) + Number(item.auditFee) + Number(item.registerFee)
        item.patentType = item.businessId
      })
      const isValidate = validateFees(contractAmountData.value, sysContractReceiptNodeBos)
      if (isValidate) {
        const params = {
          ...contractForm.value,
          partMoneyList: partMoneyList.value,
          patentpersonId: contractForm.value.patentpersonId.join(','),
          totalAmount: totalAmount.value,
          sysContractReceiptNodeBos: sysContractReceiptNodeBos.filter(item => item.receiptNode !== '' && item.receiptNode !== null && item.receiptNode !== undefined),
          sysContractAmountBos: contractAmountData.value,
          businessIds: contractAmountData.value.map(item => item.businessId).join(','),
          businessTemplateId: contractForm.value.templateName,
        }
        if (contractId.value) {
          const updateParams = {
            ...params,
            contractId: contractId.value,
          }
          contractService.update(updateParams).then((res) => {
            if (res.code === 200) {
              Message.success('修改合同成功')
              dialogVisible.value = false
              emit('update:visible', {
                visible: false,
                type: 'audit',
              })
            }
          })
        }
        else {
          contractService.add(params).then((res) => {
            if (res.code === 200) {
              Message.success('新增合同成功')
              dialogVisible.value = false
              emit('update:visible', {
                visible: false,
                type: 'submit',
              })
            }
          })
        }
      }
    }
  })
}

/**
 * 验证 contractAmountData 中的费用与 sysContractReceiptNodeBos 中的数据是否匹配。
 * @param contractAmountData - 合同项目数组
 * @param sysContractReceiptNodeBos - 收款节点数组
 * @returns {boolean} 验证结果
 */
function validateFees(contractAmountData, sysContractReceiptNodeBos) {
  const feesSum = {}
  contractAmountData.forEach((item) => {
    const { businessName } = item
    if (!feesSum[businessName]) {
      feesSum[businessName] = {
        agencyFee: 0,
        officerFee: 0,
        otherFee: 0,
      }
    }
    feesSum[businessName].agencyFee += Number.parseInt(item.agencyFee)
    feesSum[businessName].officerFee += Number.parseInt(item.officerFee)
    feesSum[businessName].otherFee += Number.parseInt(item.otherFee)
  })

  const result = contractAmountData.map((item) => {
    const { businessName } = item
    return {
      ...item,
      agencyItemFee: feesSum[businessName].agencyFee,
      officerItemFee: feesSum[businessName].officerFee,
      otherItemFee: feesSum[businessName].otherFee,
    }
  })

  for (const item of result) {
    let totalNodeAgencyFee = 0

    let totalNodeOfficerFee = 0

    let totalNodeOtherFee = 0

    item.officerFee = Number.parseFloat(item.filingFee) + Number.parseFloat(item.auditFee) + Number.parseFloat(item.registerFee)
    // 遍历每个收款节点，计算与当前项目相关的费用
    for (const node of sysContractReceiptNodeBos) {
      if (item.patentType === node.patentType) {
        totalNodeAgencyFee += Number.parseFloat(node.agencyFee)

        totalNodeOtherFee += Number.parseFloat(node.otherFee)

        totalNodeOfficerFee += Number.parseFloat(node.officerFee)
      }
    }
    if (totalNodeAgencyFee !== item.agencyItemFee) {
      Message.error('收款节点与合同金额不匹配', {
        zIndex: 9999,
      })
      return false
      // return { passed: false, message: `收款节点与合同金额不匹配 (业务: ${item.businessName)`} };
    }

    // 验证其他费用
    if (totalNodeOtherFee !== item.otherItemFee) {
      Message.error('收款节点与其他费用不匹配', {
        zIndex: 9999,
      })
      return false
    }

    // // 验证官费
    // if (totalNodeOfficerFee !== item.officerItemFee) {
    //   Message.error('收款节点与官费不匹配', {
    //     zIndex: 9999,
    //   })
    //   return false
    // }
  }
  return true
}
function handleContractPathChange(e) {
  contractForm.value.contractPath = e[0].url
  contractForm.value.fileName = e[0].name
}

function handleDrawerClose() {
  contractFormRef.value.resetFields()
  contractForm.value = {
    isBigContract: 1,
  }
  handleClearAmount()
  dialogVisible.value = false
}

function handleCustomerChange() {
  const customerId = customerList.value.find(item => item.customerId === contractForm.value.customerId)?.customerId
  contractForm.value.patentpersonId = customerId ? [customerId] : null
  if (customerId) {
    customerInformationService.getDetail(customerId).then((res) => {
      console.log(res)
      const data = res.data
      contractForm.value.patentLinkman = data.linkman
      contractForm.value.linkmanPhone = data.phone
      contractForm.value.linkmanMail = data.mail
    })
  }
}

function handleBigContractChange(e) {
  if (e === 1) {
    contractForm.value.contractStartTime = ''
    contractForm.value.contractEndTime = ''
  }
}
</script>

<template>
  <el-drawer
    v-model="dialogVisible"
    class="custom-drawer"
    size="60%"
    :show-close="false"
    :close-on-click-modal="false"
    @close="handleDrawerClose"
  >
    <template #header>
      <div class="dialog-header">
        <span class="relative top-3 text-[16px] ">
          {{ formDisabled ? '查看' : contractId ? '修改' : '新增' }}合同
        </span>
      </div>
    </template>
    <el-alert title="带 * 为必输入表单" type="warning" show-icon class="mb-3!" />
    <el-form
      ref="contractFormRef"
      v-loading="formLoading"
      :model="contractForm"
      :rules="contractFormRules"
      label-width="130px"
      :disabled="formDisabled"
      element-loading-text="数据加载中。。。。"
    >
      <el-collapse v-model="activeName" class="custom-collapse">
        <el-collapse-item name="1" title="基本信息">
          <div class="grid grid-cols-2 gap-3 mt-3">
            <el-form-item label="是否框架合同" prop="isBigContract">
              <el-segmented
                v-model="contractForm.isBigContract"
                :options="[{ value: 1, label: '否' }, { value: 0, label: '是' }]"
                @change="handleBigContractChange"
              />
            </el-form-item>
            <el-form-item label="合同类别" prop="contractType">
              <el-select
                v-model="contractForm.contractType"
                placeholder="请选择合同类别"
              >
                <el-option
                  v-for="dict in sys_contract_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="合同编号" prop="contractNo">
              <el-input
                v-model="contractForm.contractNo"
                placeholder="合同编号自动生成"
                disabled
              />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="contractForm.customerId"
                filterable
                clearable
                placeholder="请选择客户名称"
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item.customerId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="合同模式" prop="contractName">
              <el-select
                v-model="contractForm.contractName"
                placeholder="请选择合同模式"
              >
                <el-option
                  v-for="dict in sys_contractaame"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="渠道商" prop="distributorId">
              <el-select
                v-model="contractForm.distributorId"
                clearable
                filterable
                placeholder="请选择渠道商"
              >
                <el-option
                  v-for="item in distributorList"
                  :key="item.distributorId"
                  :label="item.distributorName"
                  :value="item.distributorId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="渠道费用" prop="channelFees">
              <el-input
                v-model="contractForm.channelFees"
                type="number"
                clearable
                placeholder="请输入渠道费用"
              />
            </el-form-item>
            <el-form-item label="签约主体" prop="subjectId">
              <el-select
                v-model="contractForm.subjectId"
                clearable
                filterable
                placeholder="请选择签约主体"
              >
                <el-option
                  v-for="item in contractQueryList"
                  :key="item.subjectcontractId"
                  :label="item.subjectcontractName"
                  :value="item.subjectcontractId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="第三方费用" prop="otherFee" class="custom-form-item">
              <el-input
                v-model="contractForm.otherFee"
                type="number"
                placeholder="请输入第三方费用"
              />
            </el-form-item>
            <el-form-item label="专利权人" prop="patentpersonId">
              <el-select
                v-model="contractForm.patentpersonId"
                filterable
                clearable
                multiple
                placeholder="请选择专利权人"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item.customerId"
                />
              </el-select>
            </el-form-item>
            <template v-if="contractForm.isBigContract === 0">
              <el-form-item label="合同开始时间" prop="contractStartTime">
                <el-date-picker
                  v-model="contractForm.contractStartTime"
                  clearable
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择合同开始时间"
                  class="!w-full"
                />
              </el-form-item>
              <el-form-item label="合同结束时间" prop="contractEndTime" class="w-full">
                <el-date-picker
                  v-model="contractForm.contractEndTime"
                  clearable
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择合同结束时间"
                  class="!w-full"
                />
              </el-form-item>
            </template>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="contractForm.remark"
                type="textarea"
                placeholder="请输入内容"
                :rows="4"
                input-style="height: 180px"
              />
            </el-form-item>
            <el-form-item label="合同附件" prop="contractPath" class="h-10">
              <FileUpload v-model="contractForm.ossId" :limit="1" class="wh-full" :file-type="[]" :show-file-delete="formDisabled ? false : true" @change="handleContractPathChange" />
            </el-form-item>
          </div>
        </el-collapse-item>
        <el-collapse-item v-if="contractForm.contractType === '1'" name="2" class="mt-5" title="专利信息">
          <div class="grid grid-cols-2 gap-3 mt-5">
            <el-form-item label="递交端口" prop="submitcompanyId">
              <el-select
                v-model="contractForm.submitcompanyId"
                clearable
                filterable
                placeholder="请选择递交端口"
              >
                <el-option
                  v-for="item in companyQueryList"
                  :key="item.submitcompanyId"
                  :label="item.submitcompanyName"
                  :value="item.submitcompanyId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="案件方式" prop="caseType">
              <el-select v-model="contractForm.caseType" placeholder="请输入案件方式">
                <el-option
                  v-for="dict in sys_case_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="专利联系人" prop="patentLinkman">
              <el-input
                v-model="contractForm.patentLinkman"
                placeholder="请输入专利联系人"
                clearable
              />
            </el-form-item>
            <el-form-item label="专利联系人邮箱" prop="linkmanMail">
              <el-input
                v-model="contractForm.linkmanMail"
                placeholder="请输入专利联系人邮箱"
                clearable
              />
            </el-form-item>
            <el-form-item label="专利联系人电话" prop="linkmanPhone">
              <el-input
                v-model="contractForm.linkmanPhone"
                placeholder="请输入专利联系人电话"
                clearable
                type="number"
              />
            </el-form-item>
          </div>
        </el-collapse-item>
        <el-collapse-item name="3" class="mt-5" title="合同金额">
          <div class="flex-x-between mb-2 mt-3">
            <div class="flex">
              <el-button plain type="primary" @click="handleAddAmount">
                新增
                <el-icon class="el-icon--right" size="15px">
                  <CirclePlusFilled />
                </el-icon>
              </el-button>
              <el-button plain type="danger" @click="handleClearAmount">
                清空数据
                <el-icon class="el-icon--right" size="15px">
                  <DeleteFilled />
                </el-icon>
              </el-button>
            </div>
            <div class="flex-center w-70">
              <div class="w-25">
                业务模板
              </div>
              <el-select
                v-model="contractForm.templateName"
                placeholder="请选择业务模板"
                @change="getBusinessList()"
              >
                <el-option
                  v-for="item in businessTemplateList"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateId"
                />
              </el-select>
            </div>
          </div>
          <div class="my-3 flex space-x-3">
            <div class="text-[14px]">
              是否手动确认
              <el-segmented
                v-model="contractForm.isHand"
                :options="[{ value: 1, label: '否' }, { value: 0, label: '是' }]"
                @change="handleChangeReduce"
              />
            </div>
            <div v-if="contractForm.isHand === 1" class="text-[14px]">
              是否费减:
              <el-segmented
                v-model="contractForm.isDiscounts"
                :options="[{ value: 1, label: '否' }, { value: 0, label: '是' }]"
                @change="handleChangeReduce"
              />
            </div>
            <div class="text-[14px]">
              是否收取费用
              <el-segmented
                v-model="contractForm.isMoney"
                :options="[{ value: 1, label: '否' }, { value: 0, label: '是' }]"
                @change="handleChangeReduce"
              />
            </div>
            <div v-if="contractForm.isDiscounts === 0 && contractForm.isHand === 1" class="text-[14px]">
              是否多人:
              <el-segmented
                v-model="contractForm.isMultiPerson"
                :options="[{ value: 1, label: '否' }, { value: 0, label: '是' }]"
                @change="handleChangeReduce"
              />
            </div>
          </div>
          <vxe-grid
            :data="contractAmountData"
            :columns="contractAmountColumns"
            :border="true"
            :stripe="false"
            :show-footer="true"
            :resizable="true"
            :footer-data="footerData"
            :merge-footer-items="mergeFooterItems"
            header-cell-class-name="headerCellContractClass"
          >
            <template #businessType="{ row }">
              <dict-tag :options="sys_product_name" :value="row.businessType" />
            </template>
            <template #agencyFee="{ row }">
              <el-input
                v-model.number="row.agencyFee"
                :min="0"
                :maxlength="8"
                :disabled="contractForm.isMoney === 1"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #filingFee="{ row }">
              <el-input
                v-model.number="row.filingFee"
                :min="0"
                :maxlength="8"
                class="!w-20"
                :disabled="row.businessId === '1796024658129670146' || row.businessId === '1798631228967981058' || row.businessId === '1798631332965748738'"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #auditFee="{ row }">
              <el-input
                v-model.number="row.auditFee"
                :min="0"
                class="!w-20"
                :disabled="row.businessId === '1796024658129670146' || row.businessId === '1798631228967981058' || row.businessId === '1798631332965748738'"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #registerFee="{ row }">
              <el-input
                v-model.number="row.registerFee"
                :min="0"
                class="!w-20"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #otherFee="{ row }">
              <el-input
                v-model.number="row.otherFee"
                :min="0"
                class="!w-20"
                :disabled="contractForm.isMoney === 1"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #amount="{ row }">
              <el-input
                v-model.number="row.amount"
                :min="0"
                class="!w-20"
                :disabled="contractForm.isBigContract === 0"
                @change="handleAmountChange(row)"
              />
            </template>
            <template #action="{ row }">
              <el-button text type="danger" size="small" @click="handleDelAmount(row)">
                删除
                <el-icon class="el-icon--right">
                  <DeleteFilled />
                </el-icon>
              </el-button>
            </template>
          </vxe-grid>
        </el-collapse-item>
        <el-collapse-item name="4" class="mt-5" title="收款节点">
          <vxe-grid
            class="mt-3"
            :data="paymentNodeData"
            :columns="paymentNodeColumns"
            :border="true"
            :stripe="false"
            header-cell-class-name="headerCellContractClass"
          >
            <template #receiptNode="{ row }">
              <el-select
                v-for="(item, index) in paymentNodeContentData[
                  row.type - 1
                ]"
                :key="index"
                v-model="item.receiptNode"
                clearable
                class="mb-3"
                :disabled="contractForm.isMoney === 1"
                @change="handlePaymentNodeChange(row.type - 1)"
              >
                <el-option
                  v-for="item in getContentSelectData(row, sys_proceeds_time)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
            <template #agencyFee="{ row }">
              <el-input
                v-for="(item, index) in paymentNodeContentData[
                  row.type - 1
                ]"
                :key="index + 1"
                v-model.number="item.agencyFee"
                :min="0"
                class="mb-3"
                :disabled="contractForm.isMoney === 1"
              />
            </template>
            <template #officerFee="{ row }">
              <el-input
                v-for="(item, index) in paymentNodeContentData[
                  row.type - 1
                ]"
                :key="index + 1"
                v-model.number="item.officerFee"
                :min="0"
                class="mb-3"
                :disabled="contractForm.isMoney === 1"
              />
            </template>
            <template #otherFee="{ row }">
              <el-input
                v-for="(item, index) in paymentNodeContentData[
                  row.type - 1
                ]"
                :key="index + 1"
                v-model.number="item.otherFee"
                :disabled="contractForm.isMoney === 1"
                :min="0"
                class="mb-3"
              />
            </template>
            <template #action="{ row }">
              <el-button
                text type="primary" size="small"
                :disabled="
                  paymentNodeContentData[row.type - 1] ? paymentNodeContentData[row.type - 1].length >= 3 : true" @click="handleActionPaymentNode(row.type - 1, 'add', row)"
              >
                新增
                <el-icon class="el-icon--right">
                  <CirclePlusFilled />
                </el-icon>
              </el-button>
              <el-button text type="danger" size="small" @click="handleActionPaymentNode(row.type - 1, 'delete', row)">
                删除
                <el-icon class="el-icon--right">
                  <DeleteFilled />
                </el-icon>
              </el-button>
            </template>
          </vxe-grid>
        </el-collapse-item>
        <el-collapse-item name="5" class="mt-5" title="业务及提成比例">
          <div class="mt-3">
            <el-button type="primary" plain @click="handleAddBusinessRate">
              新增
              <el-icon class="el-icon--right">
                <CirclePlusFilled />
              </el-icon>
            </el-button>
            <vxe-grid
              class="mt-3"
              :data="partMoneyList"
              :columns="businessRateColumns"
              :border="true"
              :stripe="false"
              header-cell-class-name="headerCellContractClass"
            >
              <template #roleName="{ row }">
                <el-select
                  v-model="row.roleName"
                  placeholder="请选择角色"
                >
                  <el-option
                    v-for="item in roleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </template>
              <template #userName="{ row }">
                <el-select
                  v-model="row.userId"
                  clearable
                  filterable
                  placeholder="请选择人员"
                >
                  <el-option
                    v-for="item in salesmanOptions"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId"
                  />
                </el-select>
              </template>
              <template #proportion="{ row }">
                <el-input-number
                  v-model.number="row.proportion"
                  :min="0"
                  :max="100"
                  :controls="false"
                />
              </template>
              <template #remark="{ row }">
                <el-input v-model="row.remark" placeholder="请输入备注" />
              </template>
              <template #action="{ row }">
                <el-button text type="danger" size="small" @click="handleDelBusinessRate(row)">
                  删除
                  <el-icon class="el-icon--right">
                    <DeleteFilled />
                  </el-icon>
                </el-button>
              </template>
            </vxe-grid>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :disabled="formDisabled" @click="handleSubmit">
          确定
        </el-button>
        <el-button plain type="primary" @click="handleDrawerClose">
          取消
        </el-button>
      </div>
    </template>
    <div class="close-btn flex-center" @click="handleDrawerClose">
      <el-icon>
        <CloseBold />
      </el-icon>
    </div>
  </el-drawer>
  <el-dialog
    v-model="contractAmountVisible"
    title="新增"
    append-to-body
    destroy-on-close
    width="60%"
  >
    <SearchBar :search-config="contractAmountSearConfig" @search="handleContractAmountSearch" />
    <vxe-grid
      :data="contractAmountTableData"
      :columns="contractAmountTableColumns"
      :pager-config="contractAmountPageConfig"
      class="mt-2"
      :border="true"
      :stripe="false"
      :row-config="{ keyField: 'businessId' }"
      @checkbox-all="handleContractAmountCheckChange"
      @checkbox-change="handleContractAmountCheckChange"
    >
      <template #businessType="{ row }">
        <dict-tag :options="sys_product_name" :value="row.businessType" />
      </template>
    </vxe-grid>
    <template #footer>
      <el-button type="primary" @click="handleAddContractAmount">
        确定
      </el-button>
      <el-button plain type="primary" @click="contractAmountVisible = false">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.custom-drawer {
  .el-drawer__header {
    margin-bottom: 0px;
    padding: 0;
    background: #E8F2FF;

    .dialog-header {
      flex: none;
    }
  }

  .el-drawer__footer {
    box-shadow: var(--el-box-shadow);
    padding: 10px var(--el-drawer-padding-primary);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.close-btn {
  position: fixed;
  top: 50%;
  margin-left: -65px;
  cursor: pointer;
  border: none;
  outline: none;
  width: 45px;
  height: 45px;
  font-size: 22px;
  line-height: 40px;
  text-align: center;
  background-color: var(--el-color-primary);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);

  &:hover {
    background-color: #f56c6c;

    i {
      transition: transform .5s, -webkit-transform .5s;
      transform: rotate(90deg);
    }
  }
}

.dialog-footer {
  display: flex;
}
:deep(.custom-form-item) {
  :deep(.el-form-item__content){
    display: block;
  }
  .el-form-item__content {
    display: block;
  }
}
</style>

<style>
.custom-form-item {
  .el-form-item__content {
    display: block;
  }
}
</style>
